package com.edt.ichannel.api.service.component;


import cc.edt.iceutils2.string.IceStringUtils;
import cc.edt.iceutils3.date.IceDateOperationUtils;
import cc.edt.iceutils3.date.IceDateValueUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edt.ichannel.api.common.constant.CommonConstant;
import com.edt.ichannel.api.common.entity.ActionResult;
import com.edt.ichannel.api.entiy.local.EdtApiParamEntity;
import com.edt.ichannel.api.service.EdtApiService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Component
public class RedisHandler {

    private static final Logger logger = LogManager.getLogger(RedisHandler.class);

    @Resource(name = "redisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private EdtApiService edtApiService;


    /**
     * 解析三户返回信息获得systype
     *
     * @author sl
     * @param phone 手机号
     *            调用api的参数
     * @return 如果是fase 返回null
     */
    public String getSysType(String phone) {
        String key = CommonConstant.KEY_SANHU+phone;
        String value = (String) redisTemplate.opsForValue().get(key);
        if(IceStringUtils.isNotBlank(value)){
            EdtApiParamEntity edtApiParamEntity = new EdtApiParamEntity();
            edtApiParamEntity.setPhone(phone);
            ActionResult actionResult = edtApiService.sanHu(phone,CommonConstant.INFOLIST_USER);
            if (actionResult.isSuccess()) {
                JSONObject obj = JSON.parseObject((String) actionResult.getResultList());
                value = obj.getString(CommonConstant.KEY_SYSTYPE);
                setSysType(phone,value);
                return value;
            } else {
                return null;
            }
        }else{
            return value;
        }
    }

    /**
     * 将第一次查询结果存入缓存 月底失效
     * @param phone 手机号码
     * @param sysType 三户类型
     */
    public void setSysType(String phone, String sysType) {
        String key = CommonConstant.KEY_SANHU+phone;
        int timeOut = IceDateOperationUtils.betweenSecond(new Date(), IceDateValueUtils.getEndDayOfMonth());
        redisTemplate.opsForValue().set(key,sysType,timeOut, TimeUnit.SECONDS);
    }

    /**
     * 将批次号存入缓存 保存一天
     * @param batchCode 批次号
     */
    public void setBatchCode(String batchCode){
        redisTemplate.opsForValue().set(CommonConstant.BATCH_CODE_KEY,batchCode,24, TimeUnit.HOURS);
    }

    /**
     * 获取批次号
     * @return 批次号
     */
    public String getBatchCode(){
        return (String) redisTemplate.opsForValue().get(CommonConstant.BATCH_CODE_KEY);
    }
}
